package com.cy.pj.sys.controller;



import com.cy.pj.common.annotation.AApproval;
import com.cy.pj.common.web.pojo.Input;
import com.cy.pj.common.web.pojo.JSONObject;
import com.cy.pj.sys.pojo.Approval;
import com.cy.pj.sys.service.IApprovalService;
import com.cy.pj.sys.service.IToDoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/approval")
public class ApprovalController {
    @Autowired
    IApprovalService approvalService;
    @Autowired
    IToDoService todoService;

    /**
     * 审批上报
     *
     * @param input
     * @return
     */
    @PostMapping("/reporting")
    @AApproval(opType = AApproval.REPORTING)
    @Transactional
    public JSONObject reporting(@RequestBody Input input) {
        // 开启审批流程
        approvalService.addApproval(input);
        // 上报
        input.getService().reporting(input);
        // 生成待办
        todoService.generateTodo(input);
        return new JSONObject("申请上报成功");
    }

    @PostMapping("/getApprovals")
    public JSONObject getApprovals(@RequestBody Approval approval) {
        // 查询审批
        return approvalService.findApprovals(approval);
    }

    /**
     * 查看审批详情
     *
     * @param input
     * @return
     */
    @PostMapping("/getDetail")
    @AApproval(opType = AApproval.TODO_DETAIL)
    public JSONObject todoDetail(@RequestBody Input input) {
        // 查询业务详情
        return input.getService().getDetail(input);
    }

    /**
     * 审批通过
     *
     * @param input
     * @return
     */
    @PostMapping("/pass")
    @AApproval(opType = AApproval.PASS)
    @Transactional
    public JSONObject pass(@RequestBody Input input) {
        // 完成待办
        todoService.pass(input);
        // 通过审批 并 尝试推进下一审批
        approvalService.passApproval(input);
        if (null == input.getApproval().getProcessId()) {
            // 完成整个审批流程
            input.getService().pass(input);
        } else {
            // 如果审批未完成 就生成待办（新审批）
            todoService.generateTodo(input);
        }
        return new JSONObject("审批通过成功");
    }

    /**
     * 审批驳回
     *
     * @param input
     * @return
     */
    @PostMapping("/reject")
    @AApproval(opType = AApproval.REJECT)
    public JSONObject reject(@RequestBody Input input) {
        // 完成代办
        todoService.reject(input);
        // 结束审批流程
        approvalService.rejectApproval(input);
        // 结束业务流程
        input.getService().reject(input);
        return new JSONObject("审批驳回成功");
    }
}
